/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package CONTROLLERS;

import VIEW.BackUp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

/**
 *
 * @author Belthazod
 */
public class BackupController {
    Connection connection;
    JDialog waitDialog;
    BackUp backupUI;
    JLabel backupLocationText;
    String path;
    public BackupController(BackUp backupUI, JDialog waitDialog, JLabel backupLocationText){
        this.waitDialog = waitDialog;
        this.backupUI = backupUI;
        this.backupLocationText = backupLocationText;
        checkBackupPath();
    }
    public void checkBackupPath(){
        try{
        FileInputStream remember = new FileInputStream("backup.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(remember));
        String strLine;
        strLine = br.readLine();
        if(strLine.isEmpty()){
           path = "backup"; 
           backupLocationText.setText("You haven't set the directory where backups will be saved.");
        }else{
           path = strLine;
           backupLocationText.setText("Your backups are located at:" +path);
           
        }
        }catch(FileNotFoundException fnfe){
            path="backup";
            backupLocationText.setText("You haven't set the directory where backups will be saved. It will be saved on the system folder by default.");
        }catch(IOException ioe){
            
        }
    }
    public void backupDatabase(){
        try{
        String url = "jdbc:derby:inventory";
        connection = DriverManager.getConnection(url);
        
        java.text.SimpleDateFormat todaysDate = 
        new java.text.SimpleDateFormat("yyyy-MMMMM-dd-hh-mmaa");
        String backupdirectory;
        if(path==null){
            backupdirectory = "backup/"+
        todaysDate.format((java.util.Calendar.getInstance()).getTime());
        }
        else{
            backupdirectory = path +"/"+
        todaysDate.format((java.util.Calendar.getInstance()).getTime());
        }
        int response = JOptionPane.showConfirmDialog(null, "Backup may take a while. Proceed?", "Confirm backup", JOptionPane.WARNING_MESSAGE);
        if(response == 0){
            CallableStatement cs = connection.prepareCall("CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)"); 
            cs.setString(1, backupdirectory);
            cs.execute(); 
            cs.close();
            JOptionPane.showMessageDialog(null, "Backup was successful", "Backup success", JOptionPane.INFORMATION_MESSAGE);
        }
        }catch(SQLException sqlE){
            sqlE.printStackTrace();
        }
    }
    
    public void changeBackupLocation(){
        File location = new File(path);
        
        JFileChooser j = new JFileChooser();
        j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        j.setCurrentDirectory(location);
        Integer opt = j.showSaveDialog(backupUI);
        
        if (opt == JFileChooser.APPROVE_OPTION) {
            File file = j.getSelectedFile();
            backupLocationText.setText("Your backups are located at:" + file.getAbsolutePath());

            PrintWriter pw = null;
            try {
                pw = new PrintWriter(new FileOutputStream("backup.txt", false));
            } catch (Exception e){}
                pw.println(file.getAbsolutePath());
                pw.close();

        }
    }
    
    public void restore(){
        
        try{
        
            JFileChooser j = new JFileChooser();
            File location = new File(path);
            j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            j.setCurrentDirectory(location);
            Integer opt = j.showSaveDialog(backupUI);
            
            if(opt == JFileChooser.APPROVE_OPTION){
                File file = j.getSelectedFile();
                String driver = "org.apache.derby.jdbc.EmbeddedDriver";
                Class.forName(driver).newInstance();
                
//                java.util.Properties props = new java.util.Properties();
//                System.out.print(file.getAbsolutePath());
//                String reset = "jdbc:derby:inventory;shutdown=true";
//                String link = "jdbc:derby:inventory;restoreFrom="+ file.getAbsolutePath();
//                props.setProperty("user", "ocampos");
//                props.setProperty("password", "");
//                connection = DriverManager.getConnection(link, props);
//                connection.commit();
//           connection.close();
                int response = JOptionPane.showConfirmDialog(null, "Restoring from a backup would have to log you out of the system. Proceed?", "Backup warning", JOptionPane.WARNING_MESSAGE);
                if(response == 0){
           String dbURL = "jdbc:derby:inventory;restoreFrom=" + file.getAbsolutePath()+";logDevice=c:/salesdbLog";
Connection conn = DriverManager.getConnection(dbURL);
//                String backupDirectory = backupPath + "/" + dateFormat.format(new Date());
//                String sqlstmt = "CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)";
//		CallableStatement cs = connection.prepareCall(sqlstmt); 
//		cs.setString(1, backupDirectory);
//		cs.execute(); 
//		cs.close();
conn.commit();
                JOptionPane.showMessageDialog(null, "You will now be logged out of the system", "Backup success", JOptionPane.INFORMATION_MESSAGE);

                
            }
        }
        }catch(Exception e){
            e.printStackTrace();
            return;
        }
    }
}
